package android.handler;

import org.apache.log4j.Logger;

/**
 * @author Ajie
 * @date 2021-03-15
 * @function
 */
public final class Looper {
    private static final Logger logger = Logger.getLogger(Looper.class);

    static final ThreadLocal<Looper> mThreadLocal = new ThreadLocal<>();
    final MessageQueue mQueue;

    private Looper(){
        logger.info("Looper: 构造方法，new MessageQueue");
        mQueue = new MessageQueue();
    }

    public static void prepare() {
        if (mThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be create per thread");
        }
        mThreadLocal.set(new Looper());
    }

    public static Looper myLooper() {
        return mThreadLocal.get();
    }

    public static void loop(){
        Looper looper = mThreadLocal.get();
        if (looper!=null){
            MessageQueue mQueue = looper.mQueue;
            while (true){
                Message next = mQueue.next();
                next.target.dispatchMessage(next);
            }
        }
    }
}
